<template>
<div>
  <div style="padding: 10px 0">
    <el-input style="width: 200px;margin-right: 3px" suffix-icon="el-icon-search" placeholder="请输入名称"
              v-model="username"></el-input>
    <el-input style="width: 200px;margin-right: 3px" suffix-icon="el-icon-message" placeholder="请输入邮箱"
              v-model="email"></el-input>
    <el-input style="width: 200px" suffix-icon="el-icon-position" placeholder="请输入地址"
              v-model="address"></el-input>
    <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
    <el-button type="warning" @click="reset">重置</el-button>
  </div>
  <div style="margin: 10px 0">
    <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
    <el-popconfirm
        confirm-button-text='确定'
        cancel-button-text='我再想想'
        icon="el-icon-info"
        icon-color="red"
        title="您确定要批量删除选中的用户吗？"
        @confirm="delBatch"
        class="ml-5">
      <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </el-popconfirm>
  </div>
  <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="ID" width="80"></el-table-column>
    <el-table-column prop="username" label="用户名" width="120"></el-table-column>
    <el-table-column prop="nickName" label="昵称" width="120"></el-table-column>
    <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
    <el-table-column prop="phone" label="电话" width="150"></el-table-column>
    <el-table-column prop="address" label="地址" width="160"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="success" @click="handleEdit(scope.row)" >编辑 <i class="el-icon-edit-outline"></i></el-button>
        <el-popconfirm
            confirm-button-text='确定'
            cancel-button-text='我再想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定要删除该用户吗？"
            @confirm="handleDel(scope.row.id)"
            class="ml-5">
          <el-button type="danger" slot="reference">删除 <i class="el-icon-delete"></i></el-button>
        </el-popconfirm>
        <el-popconfirm
            confirm-button-text='确定'
            cancel-button-text='我再想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定要强制下线该用户吗？"
            @confirm="handleForce(scope.row.username)"
            class="ml-5">
          <el-button v-if="" type="warning" slot="reference">强制下线 <i class="el-icon-circle-close"></i></el-button>
        </el-popconfirm>

      </template>
    </el-table-column>
  </el-table>
  <div style="padding: 10px 0">
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>

  <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="30%" center :before-close="cancle">
    <el-form label-width="80px" size="normal">
      <el-form-item label="用户名" >
        <el-input v-model="form.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="昵称" >
        <el-input v-model="form.nickname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" >
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="电话" >
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="地址" >
        <el-input v-model="form.address" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancle">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>
let socket;
let _this=this;
var onlineUsers=[];
export default {
  name: "User",
  data() {
    return {
      username: "",
      nickname:"",
      email: "",
      address: "",
      form:{},
      pageSize: 10,
      pageNum: 1,
      total: 0,
      tableData: [],
      multipleSelection:[],
      dialogFormVisible:false,
      onlineUsers:[]
    }
  },
  created() {
    this.checkRole()
    this.load()
    this.socketInit()
  },
  methods:{
    //防止普通用户恶意访问
    checkRole(){
      if (!JSON.parse(localStorage.getItem("user")).role){
        this.$message.error("权限不足，禁止访问")
        this.$router.push("/")
      }
    },
    load() {
      //请求分页查询数据
      this.request.get("/user/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
          email: this.email,
          address: this.address
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    //清空三个搜索框的内容
    reset() {
      this.username = ""
      this.email = ""
      this.address = ""
      this.load()
    },
    //添加和修改功能，有用户名查重，导致不能正常修改，待完善
    save() {
      this.request.post("/user",this.form).then(res=>{
        if (res.code=='200') {
          this.$message.success("更新成功")
          this.load()
          this.dialogFormVisible=false
        }
        else
          this.$message.error("更新失败,"+res.msg)
      })
    },
    //取消添加或修改
    cancle() {
      this.dialogFormVisible=false
      this.load()
    },
    //记录多选选中用户
    handleSelectionChange(val) {
      this.multipleSelection=val
    },
    //批量删除
    delBatch() {
      let ids=this.multipleSelection.map(v=>v.id)
      this.request.post("/user/del/batch",ids).then(res=>{
        if (res.data) {
          this.$message.success("批量删除成功")
          this.load()
        }
        else
          this.$message.error("批量删除失败")
      })
    },
    //编辑自动显示数据
    handleEdit(row) {
      this.form=row
      this.dialogFormVisible=true

    },
    //删除某个用户
    handleDel(id) {
      this.request.delete("/user/"+id).then(res=>{
        if (res.data) {
          this.$message.success("删除成功")
          this.load()
        }
        else
          this.$message.error("删除失败")
      })
    },
    //每页人数改变
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    //当前页改变
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    //新增
    handleAdd() {
      this.dialogFormVisible=true
      this.form={}
    },
    //初始化socket，获取在线用户，用于强制下线
    socketInit() {
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://www.asiawu.cn:9090/onlinechat/" + JSON.parse(localStorage.getItem("user")).username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        socket.onmessage = function (msg){
          console.log("收到数据===="+msg.data)
          for (let i=0;i<JSON.parse(msg.data).users.length;i++){
            onlineUsers.push(JSON.parse(msg.data).users[i].username)
          }
          console.log(onlineUsers)
        }
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    },
    //强制下线用户
    handleForce(username) {
      if (!onlineUsers.includes(username)) {
        this.$message.info("该用户暂未上线")
        return;
      }
      else if (username==JSON.parse(localStorage.getItem("user")).username) {
        this.$message.info("请主动退出")
        return;
      }
      //组装json
      let message = {alert: true, to: username};
      //将强制下线请求发送到服务器端
      socket.send(JSON.stringify(message));
      this.$message.success("成功");
    }
  }
}
</script>

<style scoped>

</style>